package edu.ccut.saturn.studio.core.util.log;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.ccut.saturn.studio.core.util.log.listener.Log4jLoggerListener;

/**
 * Saturn日志管理。定义了日志的5个类别：
 * LOGGER_KEY_BUNDLE_MANAGER、LOGGER_KEY_LOAD_BUNDLE_CONFIG、LOGGER_KEY_COMPONENT_RUNTIME、
 * LOGGER_KEY_LOAD_BUNDLE、LOGGER_KEY_DATABASE_CONFIG
 * 
 * @author LeslieGu
 *
 */
public class SaturnLoggerManager {
	public static final String BUNDLE_DATABASE = "edu.ccut.saturn.studio.database";
	
	public static final String DEFAULT_LEVEL = ILogger.LOGGER_LEVLE_INFO;

	private static SaturnLoggerManager instance;

	private Map<String, ILogger> loggers;

	private List<String> allLevel;

	static {
		addLoggerListener(new Log4jLoggerListener());
		instance = new SaturnLoggerManager();
	}

	public static SaturnLoggerManager getInstance() {
		return instance;
	}
	
	public static void addLoggerListener(ILoggerListener loggerListener) {
		SaturnLogger.addLoggerListener(loggerListener);
	}
	
	public static void removeLoggerListener(ILoggerListener loggerListener) {
		SaturnLogger.removeLoggerListener(loggerListener);
	}

	public ILogger getSaturnLogger(String key) {
		ILogger logger = null;
		if (loggers.containsKey(key)) {
			logger = loggers.get(key);
		} else {
			logger = new SaturnLogger(key);
			logger.setLevel(DEFAULT_LEVEL);
			
			loggers.put(key, logger);
		}

		return logger;
	}
	
	public Collection<ILogger> getSaturnLoggers() {
		return this.loggers.values();
	}
	
	public Set<String> getSaturnLoggerKeys() {
		return this.loggers.keySet();
	}
	
	public void setSaturnLogger(String key, String level) {
		ILogger logger = this.getSaturnLogger(key);
		
		if (logger != null) {
			logger.setLevel(level);
		}
	}

	public void setSaturnLoggerToDefaultLevel(String key) {
		ILogger logger = this.getSaturnLogger(key);
		
		if (logger != null) {
			logger.setLevel(DEFAULT_LEVEL);
		}
	}
	
	public List<String> getAllLevel() {
		return allLevel;
	}

	private SaturnLoggerManager() {
		this.loggers = new LinkedHashMap<String, ILogger>();
		
		this.allLevel = new ArrayList<String>();
		this.allLevel.add(ILogger.LOGGER_LEVLE_INFO);
		this.allLevel.add(ILogger.LOGGER_LEVLE_DEBUG);
		this.allLevel.add(ILogger.LOGGER_LEVLE_WARN);
		this.allLevel.add(ILogger.LOGGER_LEVLE_ERROR);
		this.allLevel.add(ILogger.LOGGER_LEVLE_FATAL);
	}
}

